package com.greenant.store.activity;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.greenant.store.R;
import com.greenant.store.adapter.MyAdapter;
import com.greenant.store.bean.ImageFloder;
import com.greenant.store.utils.Bimp;
import com.greenant.store.view.ListImageDirPopupWindow;
import com.greenant.store.view.ListImageDirPopupWindow.OnImageDirSelected;

public class ImageLoadActivity extends Activity implements OnImageDirSelected
{
	private ProgressDialog mProgressDialog;

	/**
	 * 鐎涙ê鍋嶉弬鍥︽婢堕�涜厬閻ㄥ嫬娴橀悧鍥ㄦ殶闁诧�?
	 */
	private int mPicsSize;
	/**
	 * 閸ュ墽澧栭弫浼村櫤閺堬拷婢舵氨娈戦弬鍥︽婢讹拷
	 */
	private File mImgDir;
	/**
	 * 閹碉拷閺堝娈戦崶鍓у�?
	 */
	private List<String> mImgs;

	private GridView mGirdView;
	private MyAdapter mAdapter;
	/**
	 * 娑撳瓨妞傞惃鍕窡閸斺晝琚敍宀�鏁ゆ禍搴ㄦЩ濮濄垹鎮撴稉锟芥稉顏呮�?�娴犺泛銇欓惃鍕樋濞嗏剝澹傞幓锟�
	 */
	private HashSet<String> mDirPaths = new HashSet<String>();

	/**
	 * 閹殿偅寮块幏鍨煂閹碉拷閺堝娈戦崶鍓у閺傚洣娆㈡径锟�
	 */
	private List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();

	private RelativeLayout mBottomLy;

	private TextView mChooseDir;
	private TextView mImageCount;
	int totalCount = 0;

	private int mScreenHeight;

	private ListImageDirPopupWindow mListImageDirPopupWindow;
	
	private TextView tTitle;
	private ImageView iBack;
	private TextView iConfirm;
	private Resources res;

	private Handler mHandler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			switch (msg.what) {
			case 2:
				Toast.makeText(ImageLoadActivity.this, "�?多�?�择"+MyAdapter.maxGridCount+"张图�?", 400).show();
				break;

			default:
				mProgressDialog.dismiss();
				// 娑撶iew缂佹垵鐣鹃弫鐗堝�?
				data2View();
				// 閸掓繂顫愰崠鏍х潔缁�鐑樻瀮娴犺泛銇欓惃鍒緊pupWindw
				initListDirPopupWindw();
				break;
			}			
			
		}
	};

	/**
	 * 娑撶iew缂佹垵鐣鹃弫鐗堝�?
	 */
	private void data2View()
	{
		if (mImgDir == null)
		{
			Toast.makeText(getApplicationContext(), "空文件夹",
					Toast.LENGTH_SHORT).show();
			return;
		}

		mImgs = Arrays.asList(mImgDir.list());
		/**
		 * 閸欘垯浜掗惇瀣煂閺傚洣娆㈡径鍦畱鐠侯垰绶為崪灞芥禈閻�?洨娈戠捄顖氱窞閸掑棗绱戞穱婵嗙摠閿涘本鐎径褏娈戦崙蹇撶毌娴滃棗鍞寸�涙娈戝☉鍫ｏ拷妤嬬幢
		 */
		mAdapter = new MyAdapter(getApplicationContext(), mImgs,
				R.layout.item_grid_image, mImgDir.getAbsolutePath(),mHandler);
		mGirdView.setAdapter(mAdapter);
		mImageCount.setText("切换目录");
	};

	/**
	 * 閸掓繂顫愰崠鏍х潔缁�鐑樻瀮娴犺泛銇欓惃鍒緊pupWindw
	 */
	private void initListDirPopupWindw()
	{
		mListImageDirPopupWindow = new ListImageDirPopupWindow(
				LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.7),
				mImageFloders, LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.list_dir, null));

		mListImageDirPopupWindow.setOnDismissListener(new OnDismissListener()
		{

			@Override
			public void onDismiss()
			{
				// 鐠佸墽鐤嗛懗灞炬珯妫版粏澹婇崣妯绘
				WindowManager.LayoutParams lp = getWindow().getAttributes();
				lp.alpha = 1.0f;
				getWindow().setAttributes(lp);
			}
		});
		// 鐠佸墽鐤嗛柅澶嬪閺傚洣娆㈡径鍦畱閸ョ偠鐨�?
		mListImageDirPopupWindow.setOnImageDirSelected(this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_imageload);
		
		final ActionBar actionBar = getActionBar();  
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);  
        actionBar.setCustomView(R.layout.actionbar);//鑷畾涔堿ctionBar甯冨�? 

		DisplayMetrics outMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
		mScreenHeight = outMetrics.heightPixels;

		initView();
		getImages();
		initEvent();
		
		MyAdapter.mSelectedImage.clear();
		
		res=getResources();
		
        iBack = (ImageView)findViewById(R.id.left_btn);
        iConfirm = (TextView)findViewById(R.id.right_btn);
        tTitle = (TextView)findViewById(R.id.actionbar_title);
                    
        tTitle.setText(res.getText(R.string.title_activity_add));
        
        iBack.setOnClickListener(new OnClickListener()
        {	
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
         	    finish();
			}
        	
        });
        iConfirm.setText(res.getText(R.string.action_confirm));
        iConfirm.setOnClickListener(new OnClickListener()
        {	
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//MyAdapter.mSelectedImage.;
				
				for(String tmp:MyAdapter.mSelectedImage)
					if (Bimp.max<MyAdapter.maxGridCount)
						Bimp.drr.add(tmp);
				finish();
			}
        });

	}

	/**
	 * 閸掆晝鏁ontentProvider閹殿偅寮块幍瀣簚娑擃厾娈戦崶鍓у閿涘本顒濋弬瑙勭�?�閸︺劏绻嶇悰灞芥躬鐎涙劗鍤庣粙瀣╄�? 鐎瑰本鍨氶崶鍓у閻ㄥ嫭澹傞幓蹇ョ礉閺堬拷缂佸牐骞忓姊沺g閺堬拷婢舵氨娈戦柇锝勯嚋閺傚洣娆㈡径锟�
	 */
	private void getImages()
	{
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED))
		{
			Toast.makeText(this, "请插入SD存储�?", Toast.LENGTH_SHORT).show();
			return;
		}
		// 閺勫墽銇氭潻娑樺閺夛拷
		mProgressDialog = ProgressDialog.show(this, null, "载入�?...");

		new Thread(new Runnable()
		{
			@Override
			public void run()
			{

				String firstImage = null;

				Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

				ContentResolver mContentResolver = ImageLoadActivity.this
						.getContentResolver();

				// 閸欘亝鐓＄拠顣恜eg閸滃ng閻ㄥ嫬娴�?悧锟�?
				Cursor mCursor = mContentResolver.query(mImageUri, null,
						MediaStore.Images.Media.MIME_TYPE + "=? or "
								+ MediaStore.Images.Media.MIME_TYPE + "=?",
						new String[] { "image/jpeg", "image/png" },
						MediaStore.Images.Media.DATE_MODIFIED);

				Log.e("TAG", mCursor.getCount() + "");
				while (mCursor.moveToNext())
				{
					// 閼惧嘲褰囬崶鍓у閻ㄥ嫯鐭惧锟�
					String path = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Images.Media.DATA));

					Log.e("TAG", path);
					// 閹峰灝鍩�?粭顑跨瀵姴娴�?悧鍥╂畱鐠侯垰绶�?
					if (firstImage == null)
						firstImage = path;
					// 閼惧嘲褰囩拠銉ユ禈閻�?洨娈戦悥鎯扮熅�?�板嫬鎮�?
					/*if(path.indexOf("/DCIM/Camera") == -1)   
					{   
					     continue;  
					}  	*/				
					
					File parentFile = new File(path).getParentFile();
					if (parentFile == null)
						continue;
					String dirPath = parentFile.getAbsolutePath();
					ImageFloder imageFloder = null;
					// 閸掆晝鏁ゆ稉锟芥稉鐙shSet闂冨弶顒涙径姘偧閹殿偅寮块崥灞肩娑擃亝鏋冩禒璺恒仚閿涘牅绗夐崝鐘虹箹娑擃亜鍨介弬顓ㄧ礉閸ュ墽澧栨径姘虫崳閺夈儴绻曢弰顖滄祲瑜版挻浜归�?鏍畱~~閿涳�?
					if (mDirPaths.contains(dirPath))
					{
						continue;
					} else
					{
						mDirPaths.add(dirPath);
						// 閸掓繂顫愰崠鏉媘ageFloder
						imageFloder = new ImageFloder();
						imageFloder.setDir(dirPath);
						imageFloder.setFirstImagePath(path);
					}

					int picSize = parentFile.list(new FilenameFilter()
					{
						@Override
						public boolean accept(File dir, String filename)
						{
							if (filename.endsWith(".jpg")
									|| filename.endsWith(".png")
									|| filename.endsWith(".jpeg"))
								return true;
							return false;
						}
					}).length;
					totalCount += picSize;

					imageFloder.setCount(picSize);
					mImageFloders.add(imageFloder);

					if (picSize > mPicsSize)
					{
						mPicsSize = picSize;
						mImgDir = parentFile;
					}
				}
				mCursor.close();

				// 閹殿偅寮跨�瑰本鍨氶敍宀冪窡閸斺晝娈慔ashSet娑旂喎姘ㄩ崣顖欎簰闁插﹥鏂侀崘鍛摠娴滐�?
				mDirPaths = null;

				// 闁氨鐓andler閹殿偅寮块崶鍓у鐎瑰本鍨�?
				mHandler.sendEmptyMessage(0x110);

			}
		}).start();

	}

	/**
	 * 閸掓繂顫愰崠鏈ew
	 */
	private void initView()
	{
		mGirdView = (GridView) findViewById(R.id.id_gridView);
		mChooseDir = (TextView) findViewById(R.id.id_choose_dir);
		mImageCount = (TextView) findViewById(R.id.id_total_count);

		mBottomLy = (RelativeLayout) findViewById(R.id.id_bottom_ly);

	}

	private void initEvent()
	{
		/**
		 * 娑撳搫绨抽柈銊ф畱鐢啫鐪拋鍓х枂閻愮懓鍤禍瀣╂閿涘苯鑴婇崙绨唎pupWindow
		 */
		mBottomLy.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				mListImageDirPopupWindow
						.setAnimationStyle(R.style.anim_popup_dir);
				mListImageDirPopupWindow.showAsDropDown(mBottomLy, 0, 0);

				// 鐠佸墽鐤嗛懗灞炬珯妫版粏澹婇崣妯绘
				WindowManager.LayoutParams lp = getWindow().getAttributes();
				lp.alpha = .3f;
				getWindow().setAttributes(lp);
			}
		});
	}

	@Override
	public void selected(ImageFloder floder)
	{

		mImgDir = new File(floder.getDir());
		mImgs = Arrays.asList(mImgDir.list(new FilenameFilter()
		{
			@Override
			public boolean accept(File dir, String filename)
			{
				if (filename.endsWith(".jpg") || filename.endsWith(".png")
						|| filename.endsWith(".jpeg"))
					return true;
				return false;
			}
		}));
		/**
		 * 閸欘垯浜掗惇瀣煂閺傚洣娆㈡径鍦畱鐠侯垰绶為崪灞芥禈閻�?洨娈戠捄顖氱窞閸掑棗绱戞穱婵嗙摠閿涘本鐎径褏娈戦崙蹇撶毌娴滃棗鍞寸�涙娈戝☉鍫ｏ拷妤嬬幢
		 */
		mAdapter = new MyAdapter(getApplicationContext(), mImgs,
				R.layout.item_grid_image, mImgDir.getAbsolutePath(),mHandler);
		mGirdView.setAdapter(mAdapter);
		// mAdapter.notifyDataSetChanged();
		mImageCount.setText("切换目录");
		mChooseDir.setText(floder.getName());
		mListImageDirPopupWindow.dismiss();

	}

}
